<template>
    <div class="box">
        <m_block-index-nav-bar title="选择节点及经办人"/>
        <van-nav-bar
                title="选择节点及经办人"
                left-text="返回"
                left-arrow
                @click-left="back"
                :fixed="true"
                v-if="false"
        />

        <div >
            <h2 class="tle">请选择下一步骤</h2>
            <van-cell-group >
                <van-cell title="下一步骤" >
                    <template #label>
                        <van-checkbox-group style="padding-top: 7px;">
                            <van-radio v-model="selectedNodes" :name="v.nodeId" v-for="v in (source.next||[])">{{getNodeName(v)}}</van-radio>
                        </van-checkbox-group>
                    </template>
                </van-cell>
                <van-cell title="主办人" is-link :label="getMainLabel()" @click="choose('main')"/>
                <van-cell title="经办人" is-link :label="getSponsorLabel()" @click="choose('sponsor')"/>
            </van-cell-group>
            <h2 class="tle">向以下人员发送事务提醒消息</h2>
            <van-cell-group>
                <van-cell :title="vv" v-for="vv in types">
                    <template #label>
                        <van-checkbox-group v-model="msgTargets[vv]" direction="horizontal" style="padding-top: 7px;">
                            <van-checkbox :name="v" v-for="v in msgTypes">{{v}}</van-checkbox>
                        </van-checkbox-group>
                    </template>
                </van-cell>
                <van-field v-model="msg" label="提醒内容" placeholder="" />
            </van-cell-group>

            <div class="btns">
                <van-button class="btn" type="info" @click="submit">提交</van-button>
            </div>
        </div>

        <choose_user ref="choose" @ok="chooseOk"/>
    </div>
</template>

<script>
    import M_blockIndexNavBar from "./m_blockIndexNavBar";
    import Choose_user from "./choose_user";
    import url from "../url/url";
    export default {
        name: "next",
        components: {Choose_user,M_blockIndexNavBar},
        data(){
            return {
                types: ["下一步骤", "发起人", "全部经办人"],
                msgTypes: ["站内信", "短信"],
                msgTargets: {
                    "下一步骤" : ["站内信"],
                    "发起人" : [],
                    "全部经办人" : [],
                },
                //被选中的节点
                selectedNodes: "",
                dealers: {

                },
                source: {},
                msg: ""
            }
        },
        watch:{
            selectedNodes(nv){
                this.dealers = {
                    [nv] : null
                }
                this.source.next
                    .filter(e => e.nodeId === nv)
                    .forEach(e => {
                        //主办人默认选上第一个
                        var cp = JSON.parse(JSON.stringify(e.dealer));
                        this.$set(this.dealers, nv, cp)
                    })
                console.log(this.dealers)
            }
        },
        methods:{
            back(){
                this.$router.back()
            },
            /**
             * 得到一个节点的名字
             * 如果是结束节点且没有命名，则默认给一个结束
             */
            getNodeName(v){
                console.log(v)
                if(v.nodeId.includes("EndEvent") && !v.nodeName){
                    return "结束"
                } else {
                    return v.nodeName || ""
                }
            },
            getMainLabel(){
                return ((this.dealers[this.selectedNodes]||{}).main||[]).map(e => e.utname).join(",") || "无"
            },
            getSponsorLabel(){
                return ((this.dealers[this.selectedNodes]||{}).sponsor||[]).map(e => e.utname).join(",") || "无"
            },

            choose(type){
                if(!this.selectedNodes){
                    this.$notify({
                        type:"danger",
                        message:"请选择下一步的节点"
                    })
                    return
                }
                var all = this.source.next.filter(e => e.nodeId === this.selectedNodes)[0].dealers
                // console.log("dealer is", this.dealers, this.selectedNodes)
                if(type === 'main'){
                    var dls = (this.dealers[this.selectedNodes].main)
                    if(!dls || !dls.length){
                        this.$notify({
                            type:"danger",
                            message:"没有可选的经办人"
                        })
                        return;
                    }
                    this.$refs.choose.load(all, this.dealers[this.selectedNodes].main,true)
                } else {
                    var dls = (this.dealers[this.selectedNodes].sponsor)
                    console.log(dls)
                    if(!dls || !dls.length){
                        this.$notify({
                            type:"danger",
                            message:"没有可选的经办人"
                        })
                        return;
                    }
                    this.$refs.choose.load(all, this.dealers[this.selectedNodes].sponsor, false)
                }
            },
            /**
             * 选择完毕回调
             */
            chooseOk(arg){
                if(arg.isMain){
                    //拿掉经办人中被选中的部分
                    this.dealers[this.selectedNodes].sponsor = this.dealers[this.selectedNodes].sponsor.filter(e => !arg.selected.find(ee => ee.uid === e.uid))
                    //主办人设置
                    this.dealers[this.selectedNodes].main = arg.selected
                } else {
                    // 和上面相反
                    this.dealers[this.selectedNodes].main = this.dealers[this.selectedNodes].main.filter(e => !arg.selected.find(ee => ee.uid === e.uid))
                    this.dealers[this.selectedNodes].sponsor = arg.selected
                }
                //重新设置
                this.$set(this.dealers, this.selectedNodes, this.dealers[this.selectedNodes])
            },

            /**
             * 任务提交
             *
             */
            submit(){
                var d = {
                    "id": this.$route.query.id,//"5ef422d6735be5037235f230",
                    // "nodeIds": ["EndEvent_1khmhpv"],
                    // "uids": "",
                    "nextStepNotice": this.msgTargets["下一步骤"].includes("站内信"),
                    "nextStepShort": this.msgTargets["下一步骤"].includes("短信"),
                    "startNotice": this.msgTargets["发起人"].includes("站内信"),
                    "startShort": this.msgTargets["发起人"].includes("短信"),
                    "allNotice": this.msgTargets["全部经办人"].includes("站内信"),
                    "allShort": this.msgTargets["全部经办人"].includes("短信"),
                    "message": this.msg,//"您有新的工作需要办理，流程id：900，流程：test h5(2020-06-25 12:06:46)",
                    // "bpmId": "900",
                    // "bpmName": "test h5(2020-06-25 12:06:46)",
                    // "data": {
                    //     "测试文本框": "31312321",
                    //     "测试多行文本": "321313哈哈",
                    //     "测试下拉菜单": "1",
                    //     "测试单选": "1",
                    //     "测试复选": "1,2,3",
                    //     "时间格式1": "2020-06-02 00:00:00",
                    //     "时间格式2": "2020-06-30",
                    //     "时间格式3": "08:02:02",
                    //     "测试签名": "[img]/api/bpm/workflow/download?path=/2020-06-25/7d4bafd07f834c3395ddae797544bdcd.png"
                    // },
                    // "files": [],
                    // "sign": {
                    //     "idea": "同意",
                    //     "info": "",
                    //     "files": []
                    // },
                    // "mainList": {},
                    // "agentList": {},
                    // "concurrent": false,
                    // "agent": [],
                    // "reUser": [],
                    "nextNodes": {
                        ... (() => {
                            var mp = (JSON).parse(JSON.stringify(this.dealers))//{...this.dealers}
                            console.log(mp)
                            mp[this.selectedNodes].mainUsers = mp[this.selectedNodes].main.map(e => e.uid)
                            delete mp[this.selectedNodes].main
                            mp[this.selectedNodes].supportUsers = mp[this.selectedNodes].sponsor.map(e => e.uid)
                            delete mp[this.selectedNodes].sponsor
                            return mp
                        })()
                        // "EndEvent_1khmhpv": {
                        //     "mainUsers": [],
                        //     "supportUsers": []
                        // }
                    },
                    "logId": this.$route.query.logId,//"5ef422d660b24de9b2f9d52e"
                }

                this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                });
                $.ajax({
                    type:"POST",
                    url:url.doGoToNext,//"/api/bpm/workflow/nextApprover",
                    contentType:"application/json",
                    data: JSON.stringify(d)
                }).then(r => {
                    this.$toast.clear(true)
                    if(!r.success){
                        this.$notify({
                            type: "danger",
                            message: r.errMessage
                        })
                    } else {
                        if(r.data.end){
                            this.$notify({
                                type:"success",
                                message:"提交成功，任务已完结",
                                duration: 500,
                                onClose: ()=>{
                                    this.$router.back()
                                }
                            });
                        } else {
                            this.$notify({
                                type:"success",
                                message:"提交成功",
                                duration: 500,
                                onClose:()=>{
                                    this.$router.back()
                                }
                            });
                        }
                    }
                }).fail(e => {
                    this.$toast.clear(true)
                    this.$notify({
                        type: "danger",
                        message: "提交失败"
                    })
                });
            }

        },
        mounted() {
            $.ajax({
                url: url.showNextStep /*"/api/bpm/workflow/getNextDealers"*/,
                type:"POST",
                data: JSON.stringify({id: this.$route.query.id, logId: this.$route.query.logId}),
                contentType: "application/json"
            }).then(r => {
                    if(!r.success){
                        return
                    }
                    this.source = r.data
                    //节点默认选上第一个
                    try{
                        this.selectedNodes = (this.source.next||[])[0].nodeId
                    } catch (e) {
                    }
                    //处理消息
                    this.msg = (r.data.msgTemp||"").replace(/\[(.+?)\]/g, function (a,b) {
                        try{
                            switch (b) {
                                case "流水号":
                                    return r.data.ins.id
                                case "流程名":
                                    return r.data.ins.bpmName
                            }
                        } catch (e) {
                        }
                        return ""
                    })
                });
        }
    }
</script>

<style scoped lang="less">
    .tle{
        margin: 0;
        padding: 16px 16px 16px;
        color: rgba(69, 90, 100, 0.6);
        font-weight: normal;
        font-size: 16px;
        line-height: 16px;
        text-align: left;
    }
    .van-cell{
        text-align: left;
    }
    .box{
        background: #f7f8fa;
        height: 100vh;
        box-sizing: border-box;
        overflow-y: auto;
    }
    .van-radio{
        margin-bottom: 10px;
    }
    .btns{
        padding-top: 20px;
        padding-bottom: 10px;
        text-align: center;

        .btn{
            height: 30px;
            width: 150px;
        }
    }
</style>
